﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SBB.WinForms.FileExporter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString)) {
                conn.Open();

                var cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT [File], FileExtension FROM [Upload]";

                using (var reader = cmd.ExecuteReader()) {
                    while (reader.Read()) {
                        using (var fileStream = new FileStream(String.Format("C:\\SFTP\\{0}{1}", Guid.NewGuid(), reader["FileExtension"].ToString()), FileMode.Create)) {
                            var bytes = (byte[])reader["File"];

                            fileStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
            }

            MessageBox.Show("All files in database have been exported successfully.", "Export Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
